package com.zhangtai.modules.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.Neusoft.service.NeusoftEmployeeChangeService;
import com.zhangtai.modules.constVo.ContractConst;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.*;
import com.zhangtai.modules.dto.*;
import com.zhangtai.modules.entity.common.ContractUrlEntity;
import com.zhangtai.modules.entity.contract.*;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.employee.EmployerCompanyEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.contract.ContractDicService;
import com.zhangtai.modules.service.contract.ContractEmployeeStatusService;
import com.zhangtai.modules.service.contract.ContractMangerService;
import com.zhangtai.modules.service.contract.ContractRecordService;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.service.employee.EmployerCompanyService;
import com.zhangtai.modules.vo.*;
import com.zhangtai.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.InputStream;
import java.util.*;


@RestController
@Api(tags="合同管理")
@RequestMapping("contract")
@Slf4j
public class ContractController {

    @Autowired
    private ContractEmployeeStatusService contractEmployeeStatusService;
    @Autowired
    private LoginController loginController;
    @Autowired
    private ContractMangerService contractMangerService;
    @Autowired
    private ContractMangerDao contractMangerDao;
    @Autowired
    private EmployeeInfoService employeeInfoService;
    @Autowired
    private JobController jobController;
    @Autowired
    private  OssUploadService ossUploadService;
    @Autowired
    private ContractRecordService contractRecordService;
    @Autowired
    private ContractRecordDao contractRecordDao;

    @Autowired
    private BaseMssqlServiceImpl baseMssqlService;
    @Autowired
    private ContractDicService contractDicService;

    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private NeusoftEmployeeChangeService neusoftEmployeeChangeService;
    @Autowired
    private ContractUrlDao contractUrlDao;
//    @Autowired
//    private JobDaoMssql jobDaoMssql;
//    @Autowired
//    private SsqlSalaryGoupDao ssqlSalaryGoupDao;
    @Autowired
    private EmployerCompanyDao employerCompanyDao;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private EmployerCompanyService employerCompanyService;

    @PostMapping("/getContractEmployeeList")
    @ApiOperation("获取员工合同状态列表")
    public R<PageResult<ContractEmployeeStatusEntity>> getContractEmployeeList(@RequestBody @Valid ContractEmployeeVo vo, HttpServletRequest request)throws Exception{
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
       PageResult<ContractEmployeeStatusEntity> result = contractEmployeeStatusService.
               getList(vo.getName(),vo.getStatus(),orgIds,vo.getPageNum(),vo.getPageSize());
       return R.ok(result);
    }

    @PostMapping("/getContractMangerList")
    @ApiOperation("获取合同管理列表（新签）")
    public R<PageResult<ContractNewDto>> getContractMangerList(@RequestBody @Valid ContractMangerVo vo, HttpServletRequest request)throws Exception{
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        List<Long> unitId = null;
        List<Long> jobId = null;
        List<Long> orgId = null;
        if(!StringUtils.isEmpty(vo.getJobName())){
            jobId =  baseMssqlService.findJobIdByJobName(vo.getJobName());
        }
        if(!StringUtils.isEmpty(vo.getUnitName())){
            unitId =   baseMssqlService.finOrgByOrgName(vo.getUnitName());
        }
        if(!StringUtils.isEmpty(vo.getOrgName())){
            orgId =   baseMssqlService.finOrgByOrgName(vo.getOrgName());
        }
        boolean isApply = false;
        //判断是否有查询未签署状态下的合同
        if(vo.getContractStatus().contains(0)){
            isApply = true;
        }
        PageResult<ContractNewDto> result = contractMangerService.getNewList(vo.getCode(),vo.getName(),jobId,
                unitId,orgId,vo.getHiredate(),vo.getContractStatus(),orgIds,isApply,vo.getPageNum(),vo.getPageSize());

        List<ContractNewDto> list = result.getList();
        for(ContractNewDto dto:list){
            dto.setJobName(jobController.jobMap.get(dto.getJobId()));
            dto.setOrgName(jobController.orgMap.get(dto.getOrgId()));
            dto.setUnitName(jobController.orgMap.get(dto.getUnitId()));
        }

        return R.ok(result);
    }

    @PostMapping("/getContractRenewList")
    @ApiOperation("获取合同管理列表（续签）")
    public R<PageResult<ContractRenewDto>> getContractRenewList(@RequestBody @Valid ContractMangerVo vo, HttpServletRequest request)throws Exception{
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        List<Long> unitId = null;
        List<Long> jobId = null;
        List<Long> orgId = null;
        if(!StringUtils.isEmpty(vo.getJobName())){
            jobId =  baseMssqlService.findJobIdByJobName(vo.getJobName());
        }
        if(!StringUtils.isEmpty(vo.getUnitName())){
            unitId =   baseMssqlService.finOrgByOrgName(vo.getUnitName());
        }
        if(!StringUtils.isEmpty(vo.getOrgName())){
            orgId =   baseMssqlService.finOrgByOrgName(vo.getOrgName());
        }
        boolean isApply = false;
        //判断是否有查询未签署状态下的合同
        if(vo.getContractStatus().contains(0)){
            isApply = true;
        }
        PageResult<ContractRenewDto> result = contractMangerService.getRenewList(vo.getCode(),vo.getName(),jobId,
                unitId,orgId,vo.getHiredate(),vo.getContractStatus(),vo.getStatus(),orgIds,isApply,vo.getPageNum(),vo.getPageSize());
        List<ContractRenewDto> list = result.getList();
        for(ContractRenewDto dto:list){
            dto.setJobName(jobController.jobMap.get(dto.getJobId()));
            dto.setOrgName(jobController.orgMap.get(dto.getOrgId()));
            dto.setUnitName(jobController.orgMap.get(dto.getUnitId()));
        }
        return R.ok(result);
    }

    @PostMapping("/getTerminateList")
    @ApiOperation("获取解除合同列表")
    public R<PageResult<ContractTerminateDto>> getTerminateList(@RequestBody @Valid ContractTerminateVo vo, HttpServletRequest request)throws Exception{
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        List<Long> unitId = null;
        List<Long> orgId = null;
        if(!StringUtils.isEmpty(vo.getOrgName())){
            orgId = baseMssqlService.finOrgByOrgName(vo.getOrgName());
        }
        if(!StringUtils.isEmpty(vo.getUnitName())){
            unitId = baseMssqlService.finOrgByOrgName(vo.getUnitName());
        }
        PageResult<ContractTerminateDto> result = contractMangerService.getTerminateList(vo.getCode(),vo.getName(),orgId,unitId,
                vo.getContractType(),vo.getContractTimeType(),vo.getStatus(),vo.getOperateType(),vo.getEndType(),orgIds,vo.getContractStatus(),
                vo.getPageNum(),vo.getPageSize());
        List<ContractTerminateDto> list = result.getList();
        for(ContractTerminateDto dto:list){
            dto.setJobName(jobController.jobMap.get(dto.getJobId()));
            dto.setOrgName(jobController.orgMap.get(dto.getOrgId()));
            dto.setUnitName(jobController.orgMap.get(dto.getUnitId()));
        }
        return R.ok(result);
    }

    public R saveNewContract(@RequestBody @Valid ContractNewVo vo ){
        List<ContractMangerEntity> list = contractMangerDao.selectList(new QueryWrapper<ContractMangerEntity>().eq("type",vo.getType()).eq("oid",vo.getOid()).
                eq("is_delete",0).eq("contract_status",0)
        );
        ContractMangerEntity mangerEntity ;
        boolean isNew = false;
        if(!CollectionUtils.isEmpty(list)){
            mangerEntity = list.get(0);
        }else{
            mangerEntity = new ContractMangerEntity();
            isNew = true;
        }
        EmployeeInfoEntity entity = employeeInfoService.getByIdE(vo.getOid());
        mangerEntity.setJobName(jobController.jobMap.get(entity.getJobId()));
        mangerEntity.setOrgName(jobController.orgMap.get(entity.getOrgId()));
        mangerEntity.setUnitName(jobController.orgMap.get(entity.getUnitId()));
        mangerEntity.setName(entity.getName());
        mangerEntity.setContractNo("CON"+redisIdWorker.getStringId("contract"));
        if(!ObjectUtils.isEmpty(vo.getContractType())){
            mangerEntity.setContractType(vo.getContractType());
        }
        if(!ObjectUtils.isEmpty(vo.getContractBeginDate())){
            mangerEntity.setContractBeginDate(vo.getContractBeginDate());
        }
        if(!ObjectUtils.isEmpty(vo.getCompanyId())){
            mangerEntity.setEmployerCompanyId(vo.getCompanyId());
        }
        if(!StringUtils.isEmpty(vo.getCompanyName())){
            mangerEntity.setEmployerCompany(vo.getCompanyName());
        }
        if(!StringUtils.isEmpty(vo.getContractTimeType())){
            mangerEntity.setContractTimeType(vo.getContractTimeType());
        }
        mangerEntity.setIdCard(entity.getIdcard());
        mangerEntity.setSignNer(entity.getName());
        mangerEntity.setUnitId(entity.getUnitId());
        mangerEntity.setOid(vo.getOid());
        mangerEntity.setType(vo.getType());
        mangerEntity.setOperateType(vo.getOperateType());
        mangerEntity.setCreateTime(new Date());
        mangerEntity.setCode(entity.getCode());
        if(entity.getIsReinstate().equals(0)||entity.getIsReinstate().equals(2)){
            mangerEntity.setIsReinstate(0);
        }else{
            mangerEntity.setIsReinstate(1);
        }
        mangerEntity.setHireDate(entity.getHiredate());
        mangerEntity.setGender(entity.getGender());
        ContractDicEntity dicEntity = contractDicService.getByType(vo.getType());
        ContractEmployeeStatusEntity statusEntity = contractEmployeeStatusService.getByKindAndOid(vo.getOid(),dicEntity.getKind());
        //当前种类员工合同状态信息不存在，新建一条未签约的合同状态信息
        if(ObjectUtils.isEmpty(statusEntity)){
            statusEntity = new ContractEmployeeStatusEntity();
            statusEntity.setKind(dicEntity.getKind());
            statusEntity.setName(entity.getName());
            statusEntity.setOid(entity.getOid());
            statusEntity.setUnitId(entity.getUnitId());
            statusEntity.setContractStatus( ContractConst.EMPLOYEE_STATUS_UNSIGNED);
            contractEmployeeStatusService.saveE(statusEntity);
        }

        //续签和解除合同都要存储之前活跃的合同id
        if(!ObjectUtils.isEmpty(statusEntity)&&!ContractConst.CONTRACT_TYPE_NEW.equals(entity.getType())){
            ContractRecordEntity recordEntity = contractRecordService.getByIdE(statusEntity.getRecordId());
            if(!ObjectUtils.isEmpty(recordEntity)){
                mangerEntity.setRenewContractId(recordEntity.getStartContractId());
                //离职确认  修改原合同为失效
                if(ContractConst.CONTRACT_OPERATE_DIMISSION.equals(vo.getOperateType())){
                    //上一份解除合同存在才修改，否则不予处理
                    if(!ObjectUtils.isEmpty(mangerEntity.getId())){
                        ContractMangerEntity manger= contractMangerService.getByIdE(mangerEntity.getId());
                        manger.setContractStatus(2);
                        manger.setRealEndDate(vo.getContractBeginDate());
                        contractMangerService.updateByIdE(manger);
                    }
                }
            }
        }
        //新增解约
        if(ContractConst.CONTRACT_TYPE_TERMINATE.equals(vo.getType())){
            if(ContractConst.EMPLOYEE_STATUS_UNSIGNED.equals(statusEntity.getContractStatus())){
                return R.error("员工合同处于未签约状态，无法再次解约");
            }
        }
        //新增续约/新签
        else if(ContractConst.CONTRACT_TYPE_NEW.equals(vo.getType())){
            if(ContractConst.EMPLOYEE_STATUS_SIGNED.equals(statusEntity.getContractStatus())){
                return R.error("员工合同处于已签约状态，无法再次签约");
            }
        }
        //新增hr解除
        if(ContractConst.CONTRACT_OPERATE_CHANGE.equals(vo.getOperateType())){
            ContractMangerEntity cmt = contractMangerDao.getUserContract(vo.getOid());
            if(!ObjectUtils.isEmpty(cmt)){
                return R.error("员工已存在解除合同未签署列表，无法再次签约");
            }
            List<ContractRecordDto> recordList = contractRecordDao.getPersonRecordAllList(vo.getOid());
            if(!ObjectUtils.isEmpty(vo.getRealEndDate())){
                mangerEntity.setRealEndDate(vo.getRealEndDate());
                mangerEntity.setContractBeginDate(vo.getRealEndDate());
            }
            mangerEntity.setContractTimeType("7");
            if(recordList.size() > 0){
                mangerEntity.setEmployerCompany(recordList.get(0).getEmployerCompany());
                mangerEntity.setEmployerCompanyId(recordList.get(0).getEmployerCompanyId());
            }
        }
        if(isNew){
            mangerEntity.setId(snowflakeIdWorker.nextId());
            contractMangerService.saveE(mangerEntity);
        }else{
            contractMangerService.updateByIdE(mangerEntity);
        }
        return R.ok();
    }

    @Transactional
    @ApiOperation("完成合同")
    @PostMapping("/finishContract")
    public R finishContract(@RequestBody @Valid ContractFinishVo vo){
        ContractMangerEntity entity = contractMangerService.getByIdE(vo.getId());
        if(ObjectUtils.isEmpty(entity)){
            return R.error("合同信息不存在！");
        }
        entity.setSignDate(DateUtils.parseDateYMDHMSS(vo.getCreateTime()));
        //e签宝合同url
        entity.setContractEsignUrl(vo.getDownloadDocUrl());
        //保存阿里云合同url
        entity.setContractOssUrl(uploadToOssAndUpdate(vo.getDownloadDocUrl(),entity.getIdCard()));
        entity.setContractStatus(1);
        entity.setIsSendContract(2);
        entity.setCallbackStatus(1);
        //线下签订的合同主体
        if(!ObjectUtils.isEmpty(vo.getEmployerCompany())){
            entity.setEmployerCompany(vo.getEmployerCompany());
            entity.setEmployerCompanyId(vo.getEmployerCompanyId());
        }
        //线下签订的起止日期
        if(!ObjectUtils.isEmpty(vo.getContractBeginDate())){
            entity.setContractBeginDate(vo.getContractBeginDate());
        }
        if(!ObjectUtils.isEmpty(vo.getContractEndDate())){
            entity.setContractEndDate(vo.getContractEndDate());
        }
        //线下签订的合同类型
        if(!ObjectUtils.isEmpty(vo.getContractType())){
            entity.setContractType(String.valueOf(vo.getContractType()));
        }
        //线下签订的操作类型
        if(!ObjectUtils.isEmpty(vo.getOperateType())){
            entity.setOperateType(vo.getOperateType());
        }
        //线下签订的合同期限
        if(!ObjectUtils.isEmpty(vo.getContractTimeType())){
            entity.setContractTimeType(vo.getContractTimeType());
        }

        contractMangerService.updateByIdE(entity);
        ContractDicEntity dicEntity =contractDicService.getByType(Integer.parseInt(entity.getContractType()));
        ContractEmployeeStatusEntity  statusEntity = contractEmployeeStatusService.getByKindAndOid(entity.getOid(),dicEntity.getKind());
        boolean isNewStatus = false;
        if(ObjectUtils.isEmpty(statusEntity)){
            statusEntity = new ContractEmployeeStatusEntity();
            isNewStatus = true;
        }
        //签署的是解约合同
        if(ContractConst.CONTRACT_TYPE_TERMINATE.equals(entity.getType())){
            doTerminateContract(entity,statusEntity,dicEntity,isNewStatus);
        }else{
            doNewContract(entity,statusEntity,dicEntity,isNewStatus);
        }
        return R.ok();
    }

    @PostMapping("/saveTerminateContract")
    @ApiOperation("新建解除合同")
    public R saveTerminateContract(@RequestBody @Valid RelieveVo vo){
        ContractNewVo newVo = new ContractNewVo();
        newVo.setOid(vo.getOid());
        newVo.setType(vo.getType());
        newVo.setOperateType(vo.getOperateType());
        newVo.setContractType(vo.getContractType());
        newVo.setRealEndDate(vo.getRealEndDate());
        return saveNewContract(newVo);
    }

    /**
     * 解约合同签署完成流程
     * @param entity
     * @param statusEntity
     * @param isNewStatus
     */
    private void doTerminateContract(ContractMangerEntity entity,ContractEmployeeStatusEntity statusEntity,ContractDicEntity dicEntity,boolean isNewStatus){
        List<ContractRecordEntity> list = contractRecordDao.selectList(new QueryWrapper<ContractRecordEntity>().eq("oid",entity.getOid()).eq("status",1).orderByDesc("create_time"));
        Date date = entity.getContractBeginDate();
        String contractTimeType =null;
        //更新当前最新一条台账的解约合同id
        if(!CollectionUtils.isEmpty(list)){
            ContractRecordEntity recordEntity = list.get(0);
            recordEntity.setEndContractId(entity.getId());
            recordEntity.setEndTime(date);
            recordEntity.setEndContractId(entity.getId());
            recordEntity.setEndType(ContractConst.CONTRACT_END_TYPE_CONTRACT);
            //设置当前台账为失效状态
            recordEntity.setStatus(ContractConst.RECORD_STATUS_UNVAILD);
            contractRecordDao.updateById(recordEntity);
            //更新当前签约合同结束时间为当前时间
            ContractMangerEntity startEntity = contractMangerService.getByIdE(recordEntity.getStartContractId());
            startEntity.setRealEndDate(date);
            startEntity.setContractStatus(ContractConst.CONTRACT_STATUS_UNVAILD);
            contractTimeType = startEntity.getContractTimeType();
            contractMangerService.updateByIdE(startEntity);
        }
        //将当前员工合同状态更新为失效状态
        statusEntity.setContractStatus(ContractConst.EMPLOYEE_STATUS_UNVAILD);
        if(isNewStatus){
            statusEntity.setContractEndDate(date);
            statusEntity.setKind(dicEntity.getKind());
            contractEmployeeStatusService.saveE(statusEntity);
        }else{
            statusEntity.setContractEndDate(date);
            contractEmployeeStatusService.updateByIdE(statusEntity);
        }
        //将未生效的续约合同删除
        contractMangerDao.removeRenew(entity.getOid());
        //如果是非离职的解约签署完成则新建一条新签合同
        if(!ContractConst.CONTRACT_OPERATE_DIMISSION.equals(entity.getOperateType())){
            ContractNewVo newVo = new ContractNewVo();
            newVo.setOid(entity.getOid());
            newVo.setOperateType(entity.getOperateType());

            newVo.setType(ContractConst.CONTRACT_TYPE_TRANSFER);
            newVo.setContractBeginDate(DateUtils.addDateDays(date,1));
            newVo.setCompanyId(entity.getEmployerCompanyId());
            newVo.setCompanyName(entity.getEmployerCompany());
            newVo.setContractTimeType(contractTimeType);
            newVo.setRelateId(entity.getId());
            saveNewContract(newVo);
        }
    }

    private void doNewContract(ContractMangerEntity entity,ContractEmployeeStatusEntity statusEntity,ContractDicEntity dicEntity,boolean isNewStatus){
        //新签、续签会自动将之前台账设为失效
        contractRecordService.removeRecord(entity.getOid(),dicEntity.getKind());
        //新增一条台账并设置开始合同id
        ContractRecordEntity recordEntity = new ContractRecordEntity();

        recordEntity.setStartContractId(entity.getId());
        recordEntity.setOid(entity.getOid());
        recordEntity.setStatus(ContractConst.RECORD_STATUS_VAILD);
        recordEntity.setKind(dicEntity.getKind());
        recordEntity.setCreateTime(new Date());
        recordEntity.setUnitId(entity.getUnitId());
        contractRecordService.saveE(recordEntity);
        //更新员工合同状态表信息
        statusEntity.setRecordId(recordEntity.getId());
        statusEntity.setContractBeginDate(entity.getContractBeginDate());
        statusEntity.setContractEndDate(entity.getContractEndDate());
        statusEntity.setContractStatus( ContractConst.EMPLOYEE_STATUS_SIGNED);
        if(isNewStatus){
            statusEntity.setKind(dicEntity.getKind());
            contractEmployeeStatusService.saveE(statusEntity);
        }else{
            contractEmployeeStatusService.updateByIdE(statusEntity);
        }
        if(ContractConst.CONTRACT_TYPE_NEW.equals(entity.getType())){
            neusoftEmployeeChangeService.uploadContract(entity);
        }
    }


    @PostMapping("/getRecordList")
    @ApiOperation("获取合同台账")
    public R<PageResult<ContractRecordDto>> getRecordList(@RequestBody @Valid ContractRecordVo vo,HttpServletRequest request)throws Exception{
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        List<Long> unitId = null;
        List<Long> orgId = null;
        if(!StringUtils.isEmpty(vo.getOrgName())){
            orgId =  baseMssqlService.finOrgByOrgName(vo.getOrgName());
        }
        if(!StringUtils.isEmpty(vo.getUnitName())){
            unitId =   baseMssqlService.finOrgByOrgName(vo.getUnitName());
        }

        PageResult<ContractRecordDto> result = contractRecordService.getList(vo.getCode(),vo.getName(),orgId,unitId,vo.getContractType(),
                vo.getContractTimeType(),vo.getStatus(),vo.getContractEndDate(),orgIds,vo.getPageNum(),vo.getPageSize());
        List<ContractRecordDto> list = result.getList();
        for(ContractRecordDto dto:list){
            dto.setJobName(jobController.jobMap.get(dto.getJobId()));
            dto.setOrgName(jobController.orgMap.get(dto.getOrgId()));
            dto.setUnitName(jobController.orgMap.get(dto.getUnitId()));
        }
        return R.ok(result);
    }


    public String uploadToOssAndUpdate(String url ,String idCard){
        String catlog="contract"; // 传到 合同/协议/证明文件
        InputStream inputStream = IoUtils.getInputStreamByUrl(url);
        String upload = ossUploadService.upload(inputStream, catlog,idCard+".pdf");

        return upload;
    }

    @PostMapping("/getPersonRecord")
    @ApiOperation("获取个人合同记录")
    public R<List<ContractRecordDto>> getPersonRecord(String oid){
        List<ContractRecordDto> recordEntityList = contractRecordDao.getPersonRecordAllList(Long.parseLong(oid));
        return R.ok(recordEntityList);
    }
    @PostMapping("/deleteContract")
    @ApiOperation("删除合同")
    @PreAuthorize("hasAuthority('emp:htlb:delete')")//
    public R deleteContract(String id){
        ContractMangerEntity entity = contractMangerService.getByIdE(Long.parseLong(id));
        if(!entity.getContractStatus().equals(0)){
            return R.error("合同未处于待签状态，无法删除");
        }
        contractMangerService.removeOneById(Long.parseLong(id));
        return R.ok();
    }


    @GetMapping("/getEhrContractRecord")
    @ApiOperation("将ehr合同转到hr")
    public void getEhrContractRecord(){
        log.info("同步ehr合同数据开始");
//        String date = DateUtils.format(new Date(),"yyyy-MM-dd hh:mm:ss");
//        List<Map<String,Object>> unitList = ssqlSalaryGoupDao.getCompany();
//
//        Map<Long,String> unit = new HashMap<>();
//        for(Map<String,Object> u :unitList){
//            unit.put((Long)u.get("C_OID_ORGUNIT"),u.get("C_NAME").toString());
//        }
//        unit.put(1L,"桂林彰泰实业集团有限公司");
//        Map<String,Long> company = new HashMap<>();
//        Map<Long,String> companyMap = new HashMap<>();
//        List<EmployerCompanyEntity> companyEntities = employerCompanyDao.selectList(new QueryWrapper<EmployerCompanyEntity>().eq("is_delete", 0));
//        for(EmployerCompanyEntity companyEntity:companyEntities){
//            company.put(companyEntity.getName(),companyEntity.getId());
//            companyMap.put(companyEntity.getId(),companyEntity.getName());
//        }
//        List<ContractRecordSsqlDto> list =  jobDaoMssql.getAllContractRecord(date);
////        List<Long> idcardList = jobDaoMssql.getAllContractRecordRecordId(date);
//        Map<String,Long> idcardMap = new HashMap<>();
//        List<ContractMangerEntity> mangerEntityList = new ArrayList<>();
//        List<ContractRecordEntity> recordEntityList = new ArrayList<>();
//        List<ContractEmployeeStatusEntity> statusEntities = new ArrayList<>();
//        for(ContractRecordSsqlDto dto:list){
////            ContractRecordEntity recordEntity =   contractRecordDao.selectOne(new QueryWrapper<ContractRecordEntity>()
////                    .eq("oid",dto.getOid()).eq("kind",1).eq("is_delete",0));
////            if(ObjectUtils.isEmpty(recordEntity)){
////                recordEntity = new ContractRecordEntity();  用不到
////            }
//            ContractMangerEntity mangerEntity = BeanUtilsMabach.doToDto(dto,ContractMangerEntity.class);
//            EmployeeInfoEntity entity =null;
//            List<EmployeeInfoEntity> entityList = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().eq("is_delete","0").eq("idcard",dto.getIdCard()).orderByDesc("oid"));
//            if(!CollectionUtils.isEmpty(entityList)){
//                entity = entityList.get(0);
//            }
//            if(ObjectUtils.isEmpty(entity)){
//                entity = baseMssqlService.finEmpFromMssqlByIdCard(dto.getIdCard());
//            }
//            //必须根据身份证号查询，不然双方系统oid不一致会出现重复数据
//            List<ContractMangerEntity> mangerList = contractMangerDao.selectList(new QueryWrapper<ContractMangerEntity>().eq("id_card",entity.getIdcard()).
//                    eq("is_delete",0).orderByDesc("create_time")
//            );
//            mangerEntity.setOid(entity.getOid());
//            if(!CollectionUtils.isEmpty(mangerList)){
//                ContractMangerEntity entity1 = mangerList.get(0);
//                //如果存在记录且是未签署的不做任何处理
//                if(entity1.getContractStatus().equals(0)){
//                    continue;
//                }  else{
//                    mangerEntity.setId(entity1.getId());
////                    mangerEntity.setOid(entity.getOid());
//                }
//            }
//            //如果是新增且已经加入过的不增加
//            else if(!ObjectUtils.isEmpty(idcardMap.get(dto.getIdCard()))){
//                continue;
//            }
//            mangerEntity.setJobName(jobController.jobMap.get(entity.getJobId()));
//            mangerEntity.setOrgName(jobController.orgMap.get(entity.getOrgId()));
//            mangerEntity.setUnitName(jobController.orgMap.get(entity.getUnitId()));
//            mangerEntity.setIdCard(entity.getIdcard());
//            mangerEntity.setSignNer(entity.getName());
////            mangerEntity.setUnitId(entity.getUnitId());
//            mangerEntity.setType(ContractConst.CONTRACT_TYPE_NEW);
//            mangerEntity.setOperateType(ContractConst.CONTRACT_OPERATE_ENTRY);
//            mangerEntity.setCreateTime(new Date());
//            mangerEntity.setCode(entity.getCode());
//            if(ObjectUtils.isEmpty(entity.getIsReinstate())){
//                mangerEntity.setIsReinstate(0);
//            }else if(entity.getIsReinstate().equals(0)||entity.getIsReinstate().equals(2)){
//                mangerEntity.setIsReinstate(0);
//            }else{
//                mangerEntity.setIsReinstate(1);
//            }
//            mangerEntity.setHireDate(entity.getHiredate());
//            mangerEntity.setGender(entity.getGender());
//            mangerEntity.setContractType(ContractConst.CONTRACT_MANGER_LAOB);
//            mangerEntity.setContractStatus(ContractConst.EMPLOYEE_STATUS_SIGNED);
//            Integer years = DateUtils.yearsBetween(dto.getContractBeginDate(),dto.getContractEndDate());
//            mangerEntity.setContractTimeType(years.toString());
//            mangerEntity.setHireDate(entity.getHiredate());
//            mangerEntity.setSignNer(entity.getName());
//            mangerEntity.setIsSendContract(2);
//            mangerEntity.setRelateId(entity.getOid());
//            mangerEntity.setCallbackStatus(1);
//            mangerEntity.setEmployerCompany(unit.get(dto.getEmployerCompanyId()));
//            mangerEntity.setEmployerCompanyId(company.get(unit.get(dto.getEmployerCompanyId())));
//            mangerEntity.setName(entity.getName());
//            idcardMap.put(dto.getIdCard(),999999L);
//            mangerEntityList.add(mangerEntity);
//        }
//        List<ContractUrlEntity> ulrList = contractUrlDao.selectList(new QueryWrapper<ContractUrlEntity>().
//                eq("is_delete",0).eq("status",2));
//        for(ContractUrlEntity url:ulrList){
//            ContractMangerEntity mangerEntity = new ContractMangerEntity();
//            EmployeeInfoEntity entity;
//            entity = employeeInfoService.getByIdE(url.getOid());
//            if(ObjectUtils.isEmpty(entity)){
//               continue;
//            }
//            List<ContractMangerEntity> mangerList = contractMangerDao.selectList(new QueryWrapper<ContractMangerEntity>().eq("id_card",entity.getIdcard()).
//                    eq("is_delete",0).orderByDesc("create_time")
//            );
//
//            if(!CollectionUtils.isEmpty(mangerList)){
//                ContractMangerEntity entity1 = mangerList.get(0);
//                //如果存在记录且是未签署的不做任何处理
//                if(entity1.getContractStatus().equals(0)){
//                    continue;
//                }else{
//                    mangerEntity.setId(entity1.getId());
//                }
//
//            }
//            mangerEntity.setName(entity.getName());
//            mangerEntity.setContractNo("CON"+redisIdWorker.getStringId("contract"));
//            mangerEntity.setContractStatus(ContractConst.EMPLOYEE_STATUS_SIGNED);
//            mangerEntity.setContractTimeType(entity.getContractTimeType());
//            mangerEntity.setEmployerCompany(companyMap.get(entity.getEmployerCompanyId()));
//            mangerEntity.setEmployerCompanyId(entity.getEmployerCompanyId());
//            mangerEntity.setIsSendContract(2);
//            mangerEntity.setSignDate(url.getSignedTime());
//            mangerEntity.setContractType(ContractConst.CONTRACT_MANGER_LAOB);
//            mangerEntity.setContractBeginDate(DateUtils.parseDateYMD(url.getContractStartTime()));
//            mangerEntity.setContractEndDate(DateUtils.parseDateYMD(url.getContractEndTime()));
//            Integer years = DateUtils.yearsBetween(mangerEntity.getContractBeginDate(),mangerEntity.getContractEndDate());
//            mangerEntity.setContractTimeType(years.toString());
//            mangerEntity.setSignNer(entity.getName());
//            mangerEntity.setHireDate(entity.getHiredate());
//            mangerEntity.setCreateTime(new Date());
//            mangerEntity.setIdCard(entity.getIdcard());
//            mangerEntity.setCode(entity.getCode());
//            mangerEntity.setEsignFlowId(url.getFlowId());
//            mangerEntity.setContractOssUrl(url.getContractOssUrl());
//            mangerEntity.setUnitId(entity.getUnitId());
//            mangerEntity.setUnitName(jobController.getOrgNameById(entity.getUnitId()));
//            mangerEntity.setOrgName(jobController.getOrgNameById(entity.getOrgId()));
//            mangerEntity.setJobName(jobController.getJobName(entity.getJobId()));
//            mangerEntity.setContractEsignUrl(url.getContractEsignUrl());
//            mangerEntity.setOperateType(ContractConst.CONTRACT_OPERATE_ENTRY);
//            mangerEntity.setType(ContractConst.CONTRACT_TYPE_NEW);
//            mangerEntity.setGender(entity.getGender());
//            mangerEntity.setCallbackStatus(1);
//            mangerEntity.setOid( entity.getOid());
//            mangerEntity.setRelateId(entity.getOid());
//            mangerEntityList.add(mangerEntity);
//        }
//        save(mangerEntityList,recordEntityList);
//        log.info("同步ehr合同数据结束");
    }

    @Transactional
    public void save(List<ContractMangerEntity> mangerList,List<ContractRecordEntity> recordEntities){
        for(ContractMangerEntity mangerEntity:mangerList){
            if(ObjectUtils.isEmpty(mangerEntity.getId())){
                mangerEntity.setId(snowflakeIdWorker.nextId());
                contractMangerService.saveE(mangerEntity);
            }else{
                contractMangerService.updateByIdE(mangerEntity);
            }
            boolean isRecordNew = false;
            //查询是否当前合同信息存在多条已生效的合同台账数据去重，按照oid降序搜索（共享中心oid比ehr长多了）
            List<ContractRecordEntity> recordList = contractRecordDao.selectList(new QueryWrapper<ContractRecordEntity>().eq("status",1).eq("start_contract_id",mangerEntity.getId()).orderByDesc("oid"));
            ContractRecordEntity recordEntity = new ContractRecordEntity();
            //如果不存在则为新增
            if(CollectionUtils.isEmpty(recordList)){
                isRecordNew = true;
            }else if(recordList.size()>1){
                recordEntity = recordList.get(0);
                for(int i=1;i<recordList.size();i++){
                    contractRecordService.removeOneById(recordList.get(i).getId());
                }
            }else if(recordList.size()==1){
                recordEntity = recordList.get(0);
            }
            recordEntity.setStatus(ContractConst.EMPLOYEE_STATUS_SIGNED);
            recordEntity.setUnitId(mangerEntity.getUnitId());
            recordEntity.setCreateTime(new Date());
            recordEntity.setKind(1);
            recordEntity.setOid(mangerEntity.getOid());
            recordEntity.setStartContractId(mangerEntity.getId());
            if(isRecordNew){
                contractRecordService.saveE(recordEntity);
            }else{
                contractRecordService.updateByIdE(recordEntity);
            }

            boolean isNew = false;
            ContractEmployeeStatusEntity statusEntity = contractEmployeeStatusService.getByKindAndOid(mangerEntity.getOid(),1);
            if(ObjectUtils.isEmpty(statusEntity)){
                statusEntity = new ContractEmployeeStatusEntity();
                isNew = true;
            }
            statusEntity.setContractStatus(ContractConst.EMPLOYEE_STATUS_SIGNED);
            statusEntity.setRecordId(recordEntity.getId());
            statusEntity.setContractEndDate(mangerEntity.getContractEndDate());
            statusEntity.setUnitId(mangerEntity.getUnitId());
            statusEntity.setOid(mangerEntity.getOid());
            statusEntity.setName(mangerEntity.getName());
            statusEntity.setKind(1);
            statusEntity.setContractBeginDate(mangerEntity.getContractBeginDate());
            if(isNew){
                contractEmployeeStatusService.saveE(statusEntity);
            }else{
                contractEmployeeStatusService.updateByIdE(statusEntity);
            }
        }
//        for(ContractRecordEntity recordEntity:recordEntities){
//            contractRecordService.saveE(recordEntity);
//        }
    }

    @Autowired
    private EmployeeInfoDao employeeInfoDao;
    @GetMapping("/addNewContract")
    public R addNewContract(){
        ArrayList<Long> longs = new ArrayList<>();
        longs.add(2020103000004L);
        longs.add(2020103000003L);
        longs.add(2020102900001L);
        longs.add(2020102700004L);
        longs.add(2020102600002L);
        longs.add(2020102100001L);
        longs.add(2020101200005L);
        longs.add(2020101200003L);
        longs.add(2020101000007L);
        longs.add(2020101000004L);
        longs.add(2020101000001L);
        longs.add(2020093000014L);
        longs.add(2020092900001L);
        List<EmployeeInfoEntity> employeeInfoEntities = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().in("employee_oid", longs));
        log.info("条数：{}",employeeInfoEntities.size());
//        if (CollectionUtils.isEmpty(employeeInfoEntities)){
//            return R.error("查询为空");
//        }
//        for (EmployeeInfoEntity employeeInfoEntity : employeeInfoEntities) {
//            Long oid = employeeInfoEntity.getOid();
//            ContractNewVo vo = new ContractNewVo();
//            vo.setType(ContractConst.CONTRACT_TYPE_NEW);
//            vo.setOperateType(ContractConst.CONTRACT_OPERATE_ENTRY);
//            vo.setOid(oid);
//            saveNewContract(vo);
//        }

        return R.ok();
    }

}
